package com.ideal.frame.util;

import com.google.common.base.Function;
import com.google.common.collect.Collections2;
import com.google.common.collect.Lists;
import com.ideal.frame.entity.AutoModel;
import com.ideal.frame.entity.EnumTitle;
import com.ideal.frame.entity.Option;
import com.ideal.frame.entity.TreeModel;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

public class DtoUtils {

    public static <T,I> Page<T> toPageDto(Page<I> page, Pageable pageable, Function<I, T> function) {
        List<T> dtos = toListDto(page.getContent(), function);
        return new PageImpl(dtos, pageable, page.getTotalElements());
    }

    public static <T, I> List<T> toListDto(Collection<I> content, Function<I, T> function) {
        return Lists.newArrayList(Collections2.transform(content, function));
    }

    public static List<Long> toIdList(List<? extends AutoModel> entityList) {
        return Lists.transform(entityList, (AutoModel input) ->input.getId());
    }

    public static <T extends EnumTitle> List<Option<T>> warpEnumOptionFull(T[] values) {
        List<Option<T>> options = new ArrayList<Option<T>>();
        options.add(new Option<T>("全部", null));
        for (T value : values) {
            options.add(new Option<T>(value.getText(), value));
        }
        return options;
    }

    public static <T extends EnumTitle> List<Option<T>> warpEnumOption(T[] values) {
        List<Option<T>> options = new ArrayList<Option<T>>();
        for (T value : values) {
            options.add(new Option<T>(value.getText(), value));
        }
        return options;
    }

    public static <T extends Enum> T getEnumByName(Class<T> targetType, String source) {
        for (T enumObj : targetType.getEnumConstants()) {
            if (source.equals(enumObj.name())) {
                return enumObj;
            }
        }
        return null;
    }

    public static <T extends EnumTitle> T getEnumByText(Class<T> targetType, String source) {
        for (T enumObj : targetType.getEnumConstants()) {
            if (source.equals(enumObj.getText())) {
                return enumObj;
            }
        }
        return null;
    }

    /**
     * list 格式化成树状结构
     * @param list
     * @param parentId
     * @return
     */
    public static <T extends TreeModel> List<T> formatTree(List<T> list, String parentId) {
        List<T> treeResult = new ArrayList<>();
        for (T o : list) {
            if (o.getParentId().equals(parentId)) {
                treeResult.add(o);
                List<T> children = formatTree(list, o.getNodeId());
                Collections.sort(children);
                o.setChildren(children);
            }
        }
        Collections.sort(treeResult);
        return treeResult;
    }
}
